# coding=utf-8
from contextlib import suppress

import hashids
from django.conf import settings
import binascii
from django.db.models import Model
from django.http import Http404
from django.utils.module_loading import import_string


# def decode_hashed_number(hashed_number):
#     hashId = hashids.Hashids(salt='wuhuiweface2018', min_length=20)
#     results = hashId.decode(hashed_number)
#     if results:
#         return results[0]
#     return None
#
#
# def encode_user_id(user_id, min_length=10):
#     return hashids.Hashids(min_length=min_length).encode(user_id)
#
#
# def decode_user_id(hash_user_id):
#     if not hash_user_id:
#         return
#     hash_id = hashids.Hashids(min_length=10)
#     results = hash_id.decode(hash_user_id)
#     if results:
#         return results[0]


def encode_model_ids(label, *number):
    label = int(binascii.hexlify(label.encode('utf8')), 16)
    hashId = hashids.Hashids(salt=settings.SECRET_KEY, min_length=10)
    result = hashId.encode(*[int(i) for i in number], label)
    return result


def decode_model_ids(result: str, label, ignore_error=False, *, with_label=False):
    if str(result).isdigit():
        return None
    hashId = hashids.Hashids(salt=settings.SECRET_KEY, min_length=10)
    result = hashId.decode(result)
    try:
        if label is None and len(result) == 2:
            return result[0]
        elif label is None:
            return result[:-1]
        elif isinstance(label, str):
            label = [label]
        elif isinstance(label, list):
            pass
        elif issubclass(label, Model):
            label = [label._meta.label]
        assert len(result) > 1
        assert binascii.unhexlify(hex(result[-1])[2:]).decode('utf8') in label

        if len(result) == 2:
            res = result[0]
        else:
            res = result[:-1]
        if with_label:
            return res, binascii.unhexlify(hex(result[-1])[2:]).decode('utf8')
        else:
            return res
    except (AssertionError, IndexError) as e:
        if ignore_error:
            return None
        else:
            raise Http404


def decode_hid_with_model(result: str):
    if str(result).isdigit():
        return None
    hashId = hashids.Hashids(salt=settings.SECRET_KEY, min_length=10)
    result = hashId.decode(result)
    try:

        assert len(result) > 1
        label = binascii.unhexlify(hex(result[-1])[2:]).decode('utf8').split(".")
        label.insert(0, "social")
        label.insert(2, "models")
        return result[0], import_string('.'.join(label))
    except (AssertionError, IndexError) as e:
        raise Http404
